package com.queming.service.General;

import com.queming.core.dto.BaseDto;
import com.queming.core.entity.AbstractEntity;

import com.queming.core.exception.BizException;

import com.queming.service.BaseService;

import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author chencidiao
 * @date 2022/05/07 19:59
 **/
public  abstract class GeneralServiceImpl<Entity extends AbstractEntity,Dto extends BaseDto> extends BaseService implements GeneralService<Entity,Dto> {


    @Override
    public Dto create(Dto dto) {
        Entity entity = getMapper().toEntity(dto);
        return getMapper().toDto(getRepository().save(entity));
    }

    @Override
    public Dto get(String id) {
        return getMapper().toDto(getEntity(id));
    }

    protected Entity getEntity(String id){
        Optional<Entity> optionalEntity= getRepository().findById(id);
        if (!optionalEntity.isPresent()){
            throw  new BizException(getNotFoundExceptionType());
        }
        return optionalEntity.get();
    }

    @Override
    @Transactional
    public Dto update(String id, Dto dto) {
        Entity exitsEntity = getEntity(id);
        Entity entity = getRepository().save(getMapper().updateEntity(exitsEntity, dto));
        return getMapper().toDto(entity);
    }

    @Override
    public void delete(String id) {
        Entity entity = getEntity(id);
        getRepository().delete(entity);
    }

}
